import logo from '@/assets/logo.jpg';
import './App.module.css';
import { useEffect } from 'react';
import jsonData from './json.json'
import { convert } from './conver';
import JSZip from 'jszip';
import { saveAs } from 'file-saver';

function safeAtob(base64Str: string) {
  // 检查输入字符串是否是有效的Base64编码
  const base64Regex = /^[A-Za-z0-9+/]+={0,2}$/;
  if (!base64Regex.test(base64Str)) {
    throw new Error('The string to be decoded is not correctly encoded.');
  }

  // 如果输入字符串长度不是4的倍数，添加等号'='
  while (base64Str.length % 4 !== 0) {
    base64Str += '=';
  }

  return atob(base64Str);
}


function base64ToFile(base64Data,filename) {
  // 将base64的数据部分提取出来
  const parts = base64Data.split(';base64,');
  const contentType = parts[0].split(':')[1];
  const raw = window.atob(parts[1]);

  // 将原始数据转换为Uint8Array
  const rawLength = raw.length;
  const uInt8Array = new Uint8Array(rawLength);
  for (let i = 0; i < rawLength; ++i) {
    uInt8Array[i] = raw.charCodeAt(i);
  }

  // 使用Blob对象创建File对象
  const blob = new Blob([uInt8Array],{ type: contentType });
  // return new File([blob],filename,{ type: contentType });
  saveAs(blob,filename)
}

// import * as browser from 'wxt/browser'
// https://internal-api-drive-stream.feishu.cn/space/api/box/stream/download/preview/MY6ubl5qBotoG2x1bfWc3ZnanGe/?preview_type=16
export default () => {

  const handleClick = async () => {
    // console.log('🚀 ~ handleClick ~ data:', window, document)
    // ConvertDocxToMD({}, "", data.clientVars.data.block_map, zip, '')
    function fn() {
      return window.DATA
    }

    const res = await window.sendExtMessage('run-code',{
      function: fn.toString(),
      args: []
    })

    // browser.browser.downloads.download({
    //   url: 'https://internal-api-drive-stream.feishu.cn/space/api/box/stream/download/preview/MY6ubl5qBotoG2x1bfWc3ZnanGe/?preview_type=16',
    //   filename: 'test.jpg',
    //   saveAs: false,
    //   conflictAction: 'overwrite',
    // }).then(downloadId => {
    //   browser.browser.downloads.onChanged.addListener((delta) => {
    //     if (delta.id === downloadId && delta.state && delta.state.current === 'complete') {
    //       console.log('Download completed')
    //       browser.browser.downloads.getFileIcon(downloadId).then((iconUrl) => {

    //         const zip = new JSZip()
    //         zip.generateAsync({ type: 'blob' }).then((content) => {
    //           const blob = new Blob([content],{ type: 'application/zip' })
    //           const url = URL.createObjectURL(blob)

    //           browser.browser.downloads.download({
    //             url,
    //             filename: 'test.zip',
    //             saveAs: false,
    //             conflictAction: 'overwrite',
    //           })
    //             .then((downloadId) => {
    //               console.log('Download ZIP completed')
    //             })

    //           URL.revokeObjectURL(url)
    //         })
    //       })
    //     }
    //   })
    // })

    // console.log(browser)

    if (!res.clientVars?.data) {
      console.log('没有数据')
      return
    }

    browser.runtime.sendMessage({
      action: 'transform',
      data: res,
    }).then((res) => {
      console.log('transformed',res)
    })

    // convert(res.clientVars.data.block_map,res.clientVars.data.block_sequence,res.meta.title)
    // downloadAsset()
  }
  const injectScript = (file: string,node: string) => {
    const th = document.querySelector(node);
    if (th) {
      const s = document.createElement('script');
      s.setAttribute('type','text/javascript');
      s.setAttribute('src',file);
      th.appendChild(s);
    }
  };
  injectScript(browser.runtime.getURL('/my_file.js'),'body');

  // async function downloadAsset() {
  //   browser.runtime.sendMessage({ action: "downloadFile",url: "https://internal-api-drive-stream.feishu.cn/space/api/box/stream/download/preview/MY6ubl5qBotoG2x1bfWc3ZnanGe/?preview_type=16" },{

  //   }).then(res => {
  //     console.log('Downloaded',res)
  //   });
  // }

  async function sendExtMessage(type: string,data: any) {
    window.dispatchEvent(new CustomEvent('ext-req',{ detail: { type,data } }))

    return new Promise((res) => {
      function handleResponse(e) {
        const detail = e.detail
        if (detail.type == type) {
          window.removeEventListener('ext-res',handleResponse)
          return res(detail.data)
        }
      }
      window.addEventListener('ext-res',handleResponse)
    })
  }

  // 暴露到content script的window里测试
  window.sendExtMessage = sendExtMessage



  useEffect(() => {
    console.log('1111',jsonData)
    browser.runtime.onMessage.addListener(function (request,sender,sendResponse) {
      console.log("🚀 ~ message:",request,request.action)
      if (request.action === "downloadFile") {
        const content = request.data
        const name = request.name
        console.log("🚀 ~ name:",name)

        const baseString = content.split(',')[1]
        // const blob = base64toBlob(baseString,'application/zip')
        base64ToFile(content,name)
        // saveAs(blob,name)
      }
      sendResponse()
      return true
    });
  })

  return (
    <div className='fs-document-icon' onClick={handleClick}>
      <img src={logo} alt='WXT logo' />
    </div>
  );
};